package jd.se.lend;

import jd.se.common.CurrentBook;
import jd.se.common.CurrentUser;
import jd.se.common.Utils;
import jd.se.lend.LendDao;
import jd.se.lend.Book;
import org.apache.ibatis.session.SqlSession;

import java.util.Calendar;

/**
 * @author SunJiahao
 * @date 2021-05-22 16:29
 */
public class LendService {

    public static void addLend(LendDto dto, CurrentUser currentuser) {
        SqlSession sess = Utils.openSession();
        try{
            LendDao dao = sess.getMapper(LendDao.class);

            //yyyyMM00n
            java.util.Calendar cal = java.util.Calendar.getInstance();//获得当前日期
            int year = cal.get(Calendar.YEAR);
            int month = cal.get(Calendar.MONTH)+1;//cal.get(Calendar.MONTH) 获取的月份从0开始

            String mon = month<10?("0"+month):(""+month);

            String newNum = dao.findLendNewNum(year+mon);


            dto.setB_id(year+mon+newNum);
            dto.setLender(currentuser.getUserId());


            dao.insertTeacher(dto);
            sess.commit();



        }catch(Exception e){
            sess.rollback();
            throw new RuntimeException("新增信息失败！",e);
        }finally {
            sess.close();
        }
    }
    public void setcover(CurrentBook currentBook, String filename) {

        SqlSession sess = Utils.openSession();
        try{
            LendDao dao = sess.getMapper(LendDao.class);
            dao.updatecover(currentBook.getBookId(),filename);
            sess.commit();


        }catch(Exception e){
            sess.rollback();
            throw new RuntimeException("更新头像失败！",e);
        }finally {
            sess.close();
        }
    }
    public void loadCurrentBook(CurrentBook currentBook) {

        SqlSession sess = Utils.openSession();
        try{
            LendDao dao = sess.getMapper(LendDao.class);
            Book Book = dao.findTeacherById(currentBook.getBookId());
            sess.commit();

            currentBook.setBookname(Book.getB_name());
            currentBook.setCover(Book.getCover());


        }catch(Exception e){
            sess.rollback();
            throw new RuntimeException("加载用户信息失败！",e);
        }finally {
            sess.close();
        }
    }
}

